package com.aatattoo.light_food_service.controller;

import com.aatattoo.light_food_service.entity.*;
import com.aatattoo.light_food_service.enumeration.ConstantType;
import com.aatattoo.light_food_service.service.*;
import com.aatattoo.light_food_service.utils.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author aatattoo
 * @Date 2021/12/12 2:52 上午
 * @msg:
 */
@Controller
@ResponseBody
@RequestMapping("/information")
public class InformationController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ReplyService replyService;
    @Autowired
    private RemindService remindService;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserService userService;
    @Autowired
    private DynamicImgService dynamicImgService;

    /**
     * 获取点赞信息列表
     * @param pageNum
     * @param token
     * @return
     */
    @GetMapping("/like/{pageNum}")
    public Map<String,Object> like(@PathVariable("pageNum")int pageNum,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        PageHelper.startPage(pageNum,10);
        Map<String,Object> mapData=new LinkedHashMap<>();
        List<Object> dataList=new ArrayList<>();
        List<LikeMsg> msgData=new ArrayList<>();
        Like like=new Like();
        like.setUserId(userId);
        Like likeForRemind=new Like();
        //获取用户所有动态、评论、回复
        //检查相关点赞信息并排序
        //返回点赞用户（名称头像），点赞内容，点赞时间，父类型位置
        //动态
        List<Dynamic> dynamicList = dynamicService.getDynamicForMine(userId);
        like.setType(ConstantType.LIKE_DYNAMIC.getType());
        likeForRemind.setType(ConstantType.LIKE_DYNAMIC.getType());
        dynamicList.forEach(dynamic -> {
            like.setParentId(dynamic.getId());
            List<Like> likeList = likeService.findByParentId(like);
            likeList.forEach(likeByParent->{
                LikeMsg likeMsg=new LikeMsg();
                likeMsg.setId(dynamic.getId());
                likeMsg.setType(ConstantType.LIKE_DYNAMIC.getType());
                likeMsg.setContent(dynamic.getContent());
                likeMsg.setUserId(likeByParent.getUserId());
                likeMsg.setCreateTime(likeByParent.getCreateTime());
                likeMsg.setParentId(dynamic.getId());
                msgData.add(likeMsg);
            });
            //更新动态点赞列表
            likeForRemind.setParentId(dynamic.getId());
            likeService.updateRemind(likeForRemind);
        });
        //评论
        List<Comment> commentIdList = commentService.findByUserId(userId);
        like.setType(ConstantType.LIKE_COMMENT.getType());
        likeForRemind.setType(ConstantType.LIKE_COMMENT.getType());
        commentIdList.forEach(comment->{
            like.setParentId(comment.getId());
            List<Like> likeList = likeService.findByParentId(like);
            likeList.forEach(likeByParent->{
                LikeMsg likeMsg=new LikeMsg();
                likeMsg.setId(comment.getId());
                likeMsg.setType(ConstantType.LIKE_COMMENT.getType());
                likeMsg.setContent(comment.getContent());
                likeMsg.setUserId(likeByParent.getUserId());
                likeMsg.setCreateTime(likeByParent.getCreateTime());
                likeMsg.setParentId(comment.getDynamicId());
                msgData.add(likeMsg);
            });
            //更新评论点赞列表
            likeForRemind.setParentId(comment.getId());
            likeService.updateRemind(likeForRemind);
        });
        //回复
        List<Reply> replyList = replyService.findActiveByUserId(userId);
        like.setType(ConstantType.LIKE_REPLY.getType());
        likeForRemind.setType(ConstantType.LIKE_REPLY.getType());
        replyList.forEach(reply->{
            like.setParentId(reply.getId());
            List<Like> likeList = likeService.findByParentId(like);
            likeList.forEach(likeByParent->{
                LikeMsg likeMsg=new LikeMsg();
                likeMsg.setId(reply.getId());
                likeMsg.setType(ConstantType.LIKE_REPLY.getType());
                likeMsg.setContent(reply.getContent());
                likeMsg.setUserId(likeByParent.getUserId());
                likeMsg.setCreateTime(likeByParent.getCreateTime());
                likeMsg.setParentId(reply.getCommentId());
                msgData.add(likeMsg);
            });
            //更新回复点赞列表
            likeForRemind.setParentId(reply.getId());
            likeService.updateRemind(likeForRemind);
        });
        //排序
        msgData.sort(Comparator.comparing(LikeMsg::getCreateTime).reversed());
        System.out.println(msgData);
        PageInfo pageInfo = new PageInfo(msgData);
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
        pageInfo.getList().forEach(likeByPage->{
            LikeMsg likeMsg=(LikeMsg)likeByPage;
            Map<String,Object> msgMap=new LinkedHashMap<>();
            Map<String,Object> parentMap=new LinkedHashMap<>();
            Map<String, Object> userMap = userService.getUserMap(likeMsg.getUserId());
            msgMap.put("user",userMap);
            switch (likeMsg.getType()){
                case 1:
                    //动态
                    msgMap.put("type",ConstantType.LIKE_DYNAMIC.getType());
                    Dynamic dynamicForDynamic = dynamicService.findById(likeMsg.getParentId());
                    parentMap.put("dynamicId",dynamicForDynamic.getId());
                    parentMap.put("dynamicContent",dynamicForDynamic.getContent());
                    parentMap.put("dynamicImg",dynamicForDynamic.getHaveImg()
                            ==ConstantType.DYNAMIC_IMG.getType()
                            ?dynamicImgService.findFirstByDynamicId(dynamicForDynamic.getId()):"");
                    break;
                case 2:
                    //评论
                    msgMap.put("type",ConstantType.LIKE_COMMENT.getType());
                    Dynamic dynamicForComment = dynamicService.findById(likeMsg.getParentId());
                    parentMap.put("dynamicId",dynamicForComment.getId());
                    parentMap.put("dynamicContent",dynamicForComment.getContent());
                    parentMap.put("dynamicImg",dynamicForComment.getHaveImg()
                            ==ConstantType.DYNAMIC_IMG.getType()
                            ?dynamicImgService.findFirstByDynamicId(dynamicForComment.getId()):"");
                    break;
                case 3:
                    //回复
                    msgMap.put("type",ConstantType.LIKE_REPLY.getType());
                    Comment comment = commentService.findByCommentId(likeMsg.getParentId());
                    Dynamic dynamicForReply = dynamicService.findById(comment.getDynamicId());
                    parentMap.put("commentId",comment.getId());
                    parentMap.put("commentContent",comment.getContent());
                    parentMap.put("dynamicId",dynamicForReply.getId());
                    parentMap.put("dynamicContent",dynamicForReply.getContent());
                    parentMap.put("dynamicImg",dynamicForReply.getHaveImg()
                            ==ConstantType.DYNAMIC_IMG.getType()
                            ?dynamicImgService.findFirstByDynamicId(dynamicForReply.getId()):"");
                    break;
                default:
                    break;
            }
            msgMap.put("id",likeMsg.getId());
            msgMap.put("content",likeMsg.getContent());
            msgMap.put("createTime",TimeUtil.timestampFormat(likeMsg.getCreateTime()));
            msgMap.put("parent",parentMap);
            dataList.add(msgMap);
        });
        mapData.put("like",dataList);
        return mapData;
    }

    /**
     * 获取粉丝信息列表
     * @param pageNum
     * @param token
     * @return
     */
    @GetMapping("/fans/{pageNum}")
    public Map<String,Object> fans(@PathVariable("pageNum")int pageNum,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        PageHelper.startPage(pageNum,10);
        Map<String,Object> mapData=new LinkedHashMap<>();
        List<Object> dataList=new ArrayList<>();
        //获取用户的粉丝列表
        //粉丝头像，名称，关注时间
        List<UserFollow> fansList = userFollowService.fansFindById(userId);
        PageInfo pageInfo = new PageInfo(fansList);
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
        pageInfo.getList().forEach(fansByPage->{
            UserFollow userFollow=(UserFollow)fansByPage;
            Map<String, Object> userMap = userService.getUserMap(userFollow.getFansId());
            userMap.put("createTime",TimeUtil.timestampFormat(userFollow.getCreateTime()));
            dataList.add(userMap);
        });
        mapData.put("fans",dataList);
        //更新粉丝列表信息remind状态
        userFollowService.updateRemind(userId);
        return mapData;
    }

    /**
     * 获取@消息列表
     * @param pageNum
     * @param token
     * @return
     */
    @GetMapping("/remind/{pageNum}")
    public Map<String,Object> remind(@PathVariable("pageNum")int pageNum,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        Map<String,Object> mapData=new LinkedHashMap<>();
        List<Object> dataList=new ArrayList<>();
        PageHelper.startPage(pageNum,10);
        //获取@列表
        List<Remind> remindList = remindService.findByPassive(userId);
        PageInfo pageInfo = new PageInfo(remindList);
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
        //确定类型，找到父内容
        //用户（id，名字，头像）@的文本内容 @父内容
        pageInfo.getList().forEach(remindByPage->{
            Remind remind=(Remind)remindByPage;
            Map<String,Object> data=new LinkedHashMap<>();
            Map<String,Object> msgMap=new LinkedHashMap<>();
            Map<String,Object> parentMap = new LinkedHashMap<>();
            Map<String, Object> userMap = userService.getUserMap(remind.getActiveId());
            data.put("user",userMap);
            msgMap.put("id",remind.getParentID());
            if (remind.getType()==ConstantType.REMIND_DYNAMIC.getType()){
                //动态
                Dynamic dynamic = dynamicService.findById(remind.getParentID());
                msgMap.put("type",1);
                msgMap.put("content",dynamic.getContent());
                msgMap.put("createTime",TimeUtil.timestampFormat(dynamic.getCreateTime()));
                parentMap.put("dynamicId",dynamic.getId());
                parentMap.put("dynamicContent",dynamic.getContent());
                parentMap.put("dynamicImg",dynamic.getHaveImg()
                        ==ConstantType.DYNAMIC_IMG.getType()
                        ?dynamicImgService.findFirstByDynamicId(dynamic.getId()):"");
                msgMap.put("parent",parentMap);
            } else if (remind.getType()==ConstantType.REMIND_COMMENT.getType()) {
               //评论
                Comment commet = commentService.findByCommentId(remind.getParentID());
                msgMap.put("type",2);
                msgMap.put("content",commet.getContent());
                msgMap.put("createTime",TimeUtil.timestampFormat(commet.getCreateTime()));
                Dynamic dynamic = dynamicService.findById(commet.getDynamicId());
                parentMap.put("dynamicId",dynamic.getId());
                parentMap.put("dynamicContent",dynamic.getContent());
                parentMap.put("dynamicImg",dynamic.getHaveImg()
                        ==ConstantType.DYNAMIC_IMG.getType()
                        ?dynamicImgService.findFirstByDynamicId(dynamic.getId()):"");
                msgMap.put("parent",parentMap);
            }else {
               //回复
                Reply reply = replyService.findById(remind.getParentID());
                msgMap.put("type",3);
                msgMap.put("content",reply.getContent());
                msgMap.put("createTime",TimeUtil.timestampFormat(reply.getCreateTime()));
                Comment commet = commentService.findByCommentId(remind.getParentID());
                Dynamic dynamic = dynamicService.findById(commet.getDynamicId());
                parentMap.put("commentId",commet.getId());
                parentMap.put("commentContent",commet.getContent());
                parentMap.put("dynamicId",dynamic.getId());
                parentMap.put("dynamicContent",dynamic.getContent());
                parentMap.put("dynamicImg",dynamic.getHaveImg()
                        ==ConstantType.DYNAMIC_IMG.getType()
                        ?dynamicImgService.findFirstByDynamicId(dynamic.getId()):"");
                msgMap.put("parent",parentMap);

           }
            data.put("message",msgMap);
            dataList.add(data);
        });
        //更新@用户的remind状态
        remindService.updataRemind(userId);
        mapData.put("remind",dataList);
        return mapData;
    }

    /**
     * 获取评论、回复消息列表
     */
    @GetMapping("/comment/{pageNum}")
    public Map<String,Object> comment(@PathVariable("pageNum")int pageNum,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        List<CommentMsg> msgData=new ArrayList<>();
        PageHelper.startPage(pageNum,10);
        List<Object> dataList=new ArrayList<>();
        //获取评论和回复的列表
        //用户自己动态下的所有评论，  用户自己评论下的所有回复
        //用户（名称，头像）类型（评论，回复），内容（评论，回复内容），时间，动态正文和一张图片，回复多包含一个评论正文
        //评论获取：获取所有动态->获取所有评论
        List<Integer> dynamicIdList = dynamicService.getDynamicIdForMine(userId);
        dynamicIdList.forEach(dynamicId->{
            List<Comment> commentList = commentService.findByDynamicId(dynamicId);
            commentList.forEach(comment -> {
                if (comment.getUserId()!=userId){
                    CommentMsg commentMsg=new CommentMsg();
                    commentMsg.setId(comment.getId());
                    commentMsg.setType(ConstantType.MSG_COMMENT.getType());
                    commentMsg.setUserId(comment.getUserId());
                    commentMsg.setContent(comment.getContent());
                    commentMsg.setCreateTime(comment.getCreateTime());
                    commentMsg.setParentId(dynamicId);
                    msgData.add(commentMsg);
                    //更新评论remind状态
                    commentService.updataRemind(comment.getId());
                }
            });
        });
        List<Reply> replyList = replyService.findPassiveByUserId(userId);
        replyList.forEach(reply -> {
            if (reply.getActiveId()!=userId){
                CommentMsg commentMsg=new CommentMsg();
                commentMsg.setId(reply.getId());
                commentMsg.setType(ConstantType.MSG_REPLY.getType());
                commentMsg.setUserId(reply.getActiveId());
                commentMsg.setContent(reply.getContent());
                commentMsg.setCreateTime(reply.getCreateTime());
                commentMsg.setParentId(reply.getCommentId());
                msgData.add(commentMsg);
            }
        });
        //更新回复remind状态
        replyService.updataRemind(userId);
        //排序
        msgData.sort(Comparator.comparing(CommentMsg::getCreateTime).reversed());
        //分页
        PageInfo pageInfo = new PageInfo(msgData);
        Map<String,Object> mapData=new LinkedHashMap<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
        pageInfo.getList().forEach(comment->{
            CommentMsg commentData= (CommentMsg) comment;
            Map<String,Object> data=new LinkedHashMap<>();
            Map<String, Object> userMap = userService.getUserMap(commentData.getUserId());
            LinkedHashMap<Object, Object> commentMap = new LinkedHashMap<>();
            LinkedHashMap<Object, Object> parentMap = new LinkedHashMap<>();
            data.put("user",userMap);
            if (commentData.getType()==0){
                //评论
                Dynamic dynamic = dynamicService.findById(commentData.getParentId());
                parentMap.put("dynamicId",dynamic.getId());
                parentMap.put("dynamicContent",dynamic.getContent());
                parentMap.put("dynamicImg",dynamic.getHaveImg()
                        ==ConstantType.DYNAMIC_IMG.getType()
                        ?dynamicImgService.findFirstByDynamicId(dynamic.getId()):"");
//                parentMap.put("dynamicImg",dynamic.getHaveImg()
//                        ==ConstantType.DYNAMIC_IMG.getType()
//                        ?dynamicImgService.findFirstByDynamicId(commentData.getParentId()):"");
                //统一json结果1，动态，2评论，3回复
                commentMap.put("type",2);
            }else {
                //回复
                Comment commentById = commentService.findByCommentId(commentData.getParentId());
                Dynamic dynamic = dynamicService.findById(commentById.getDynamicId());
                parentMap.put("commentId",commentById.getId());
                parentMap.put("commentContent",commentById.getContent());
                parentMap.put("dynamicId",dynamic.getId());
                parentMap.put("dynamicContent",dynamic.getContent());
//                parentMap.put("dynamicImg",dynamic.getHaveImg()
//                        ==ConstantType.DYNAMIC_IMG.getType()
//                        ?dynamicImgService.findFirstByDynamicId(commentData.getParentId()):"");
                parentMap.put("dynamicImg",dynamic.getHaveImg()
                        ==ConstantType.DYNAMIC_IMG.getType()
                        ?dynamicImgService.findFirstByDynamicId(dynamic.getId()):"");
                commentMap.put("type",3);
            }
            commentMap.put("id",commentData.getId());
            commentMap.put("content",commentData.getContent());
            commentMap.put("createTime", TimeUtil.timestampFormat(commentData.getCreateTime()));
            commentMap.put("parent",parentMap);
            data.put("message",commentMap);
            dataList.add(data);
        });
        mapData.put("comment",dataList);
        return mapData;
    }

    /**
     * 处理消息中心评论、@、新粉丝、赞的未查看信息数目
     * @param token 用户token
     * @return
     */
    @GetMapping("/countUnreadMsg")
    public Map<String,Integer>msgReminder(@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        Map<String,Integer> mapData=new LinkedHashMap<>();
        int msgCount=0;
        int remindCount;
        int fansCount;
        int likeCount=0;
        Like like=new Like();
        like.setUserId(userId);
        //获取评论，二级评论的未查看数目(获取数量->修改查看状态)
        //一级评论：获取当前用户发送的动态Id，查找在此动态下未查看的评论数量
        List<Integer> dynamicIdList = dynamicService.getDynamicIdForMine(userId);
        like.setType(ConstantType.LIKE_DYNAMIC.getType());
        for (Integer dynamicId : dynamicIdList) {
            Comment comment=new Comment();
            comment.setDynamicId(dynamicId);
            comment.setUserId(userId);
            int commentNum = commentService.countRemind(comment);
            msgCount = msgCount + commentNum;
            like.setParentId(dynamicId);
            int likeDynamicNum = likeService.countRemind(like);
            likeCount=likeCount+likeDynamicNum;
        }
        //二级评论：查看是否有回复当前用户的评论，未查看的数量
        msgCount=msgCount+replyService.countRemind(userId);
        //@功能为查看信息数目
        remindCount=remindService.countRemind(userId);
        //粉丝未查看信息数目
        fansCount=userFollowService.countRemind(userId);
        //点赞未查看信息数目（动态<一级评论处处理>，评论，回复）
        List<Comment> commentList = commentService.findByUserId(userId);
        like.setType(ConstantType.LIKE_COMMENT.getType());
        for (Comment comment:commentList){
            like.setParentId(comment.getId());
            int likeCommentNum = likeService.countRemind(like);
            likeCount=likeCount+likeCommentNum;
        }
        List<Reply> replyList=replyService.findActiveByUserId(userId);
        like.setType(ConstantType.LIKE_REPLY.getType());
        for (Reply reply : replyList) {
            like.setParentId(reply.getId());
            int likeReplyNum = likeService.countRemind(like);
            likeCount=likeCount+likeReplyNum;
        }
        mapData.put("countComment",msgCount);
        mapData.put("countRemind",remindCount);
        mapData.put("countFans",fansCount);
        mapData.put("countLike",likeCount);
        return mapData;
    }


}
